package handler

import (
	"context"
	"fmt"
	"order/dao/mysql"
	"order/proto"
	"order/utils"
	"strconv"
)

type Order struct{}

// Return a new handler
func New() *Order {
	return &Order{}
}

// Call is a single request handler called via client.Call or the generated client code
func (e *Order) PostOrders(ctx context.Context, in *order.OrderReq) (*order.OrderResp, error) {
	orderId, err := mysql.SubmitOrder(in.HouseId, in.StartDate, in.EndDate, in.UserName)
	if err != nil {
		return &order.OrderResp{
			Errno:  utils.RECODE_DBERR,
			Errmsg: utils.RecodeText(utils.RECODE_DBERR),
			Data:   nil,
		}, nil
	}

	return &order.OrderResp{
		Errno:  utils.RECODE_OK,
		Errmsg: utils.RecodeText(utils.RECODE_OK),
		Data: &order.OrderData{
			OrderId: strconv.Itoa(int(orderId)),
		},
	}, nil

}

func (e *Order) GetOrders(ctx context.Context, in *order.GetReq) (*order.GetResp, error) {
	orderData, err := mysql.GetOrders(in.UserName, in.Role)
	if err != nil {
		fmt.Println("GetOrders err: ", err)
		return &order.GetResp{
				Errno:  utils.RECODE_DBERR,
				Errmsg: utils.RecodeText(utils.RECODE_DBERR),
				Data:   nil,
			},
			nil
	}

	return &order.GetResp{
		Errno:  utils.RECODE_OK,
		Errmsg: utils.RecodeText(utils.RECODE_OK),
		Data: &order.GetData{
			Orders: orderData,
		},
	}, nil
}

func (e *Order) UpdateStatus(ctx context.Context, in *order.UpdateReq) (*order.UpdateResp, error) {
	err := mysql.UpdateStatus(in.Action, in.Id, in.Reason)
	if err != nil {
		return &order.UpdateResp{
			Errno:  utils.RECODE_DBERR,
			Errmsg: utils.RecodeText(utils.RECODE_DBERR),
		}, nil
	}

	return &order.UpdateResp{
		Errno:  utils.RECODE_OK,
		Errmsg: utils.RecodeText(utils.RECODE_OK),
	}, nil

}

func (e *Order) PutComment(ctx context.Context, in *order.CommentReq) (*order.UpdateResp, error) {
	err := mysql.PutComment(in.Orderid, in.Comment)
	if err != nil {
		return &order.UpdateResp{
			Errno:  utils.RECODE_DBERR,
			Errmsg: utils.RecodeText(utils.RECODE_DBERR),
		}, nil
	}

	return &order.UpdateResp{
		Errno:  utils.RECODE_OK,
		Errmsg: utils.RecodeText(utils.RECODE_OK),
	}, nil
}
